package assignment6;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 * Class with associated methods for reading Morse code from a file or text pane
 * and deciphering Morse code
 * 
 * @author Terry Wasserleben CS204-21370 Prof. Jeannette Myers Due: 11/2/2011
 */
public class MorseCodeConverter {
	
	// Error: Strings
	/**
	 * static String to able to be used in multiple locations
	 */
	private static String errorFileNotFound = "Error!\n\nThis file is not found.\nPlease, choose another file";
	
	/**
	 * creates relationship
	 */
	private MorseCodeTree mct;
	
	/**
	 * Constructor for Morse code data structures
	 */
	public MorseCodeConverter() {
		mct = new MorseCodeTree();
	}
	
	/**
	 * Method modularizes the error dialog
	 * 
	 * @param temp String parameter for displayed message
	 */
	private void errorDialog(String temp) {
		JOptionPane.showMessageDialog(null, temp);
	}
	
	/**
	 * Method to convert Morse code to English from a file
	 * 
	 * @param file File parameter passed of file to be read from and translated
	 * @return String returned after conversion
	 */
	public String convertToEnglish(File file) {
		String result = "";
		Scanner in = null;
		try {
			FileInputStream reader = new FileInputStream(file);
			in = new Scanner(reader);
			in.useDelimiter("/");
			while (in.hasNext()) {
				result += mct.getWord(in.next());
				result += " ";
			}
		}
		catch (FileNotFoundException e) {
			errorDialog(errorFileNotFound);
			convertToEnglish(chooserDialog());
		}
		finally {
			in.close();
		}
		return result;
	}
	
	/**
	 * Method to convert Morse code to English from the program
	 * 
	 * @param text String parameter passed to be read from and translated
	 * @return String returned after conversion
	 */
	public String convertToEnglish(String text) {
		String result = "";
		Scanner inString = new Scanner(text);
		inString.useDelimiter("/");
		while (inString.hasNext()) {
			result += mct.getWord(inString.next());
			result += " ";
		}
		inString.close();
		return result;
	}
	
	/**
	 * Dialog to select file and return
	 * 
	 * @return File return selected file
	 */
	public File chooserDialog() {
		File tempFile = null;
		JFileChooser chooser = new JFileChooser();
		if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			tempFile = chooser.getSelectedFile();
		}
		return tempFile;
	}
	
}
